import sys
import getopt

dyz_filename = None	# dyz = duo yin zi
opts, args = getopt.getopt(sys.argv[1:], '-f:', ['filename='])
for opt_name, opt_val in opts:
	if opt_name in ('-f', '--filename'):
		dyz_filename = opt_val

f = open('gb2312.txt', 'r', encoding='utf-8')	# hz-freq.txt
gb2312_set = set(f.read().split())
f.close()

py_set = set()
hz_set = set()
dic = {}
f = open('py-tbl.txt', 'r', encoding='utf-8')
for line in f:
	try:
		(py, all_hz) = line.split()
	except Exception:
		continue
	py = py.replace('-', '')	
	if py in py_set:
		print(py, '已出现过。')
	py_set.add(py)
	for hz in all_hz:
		dic.setdefault(hz, []).append(py)
		hz_set.add(hz)
f.close()
	
print('共计', len(py_set), '个拼音，', len(hz_set), '个汉字', sep='')

if dyz_filename:
	f = open(dyz_filename, 'w', encoding='utf-8')
	for hz in dic.keys():
		if hz in gb2312_set and len(dic[hz]) > 1:
			print(hz, file=f)
	f.close()

while True:
	try:
		hz = input('请输入一个汉字：')
		print(dic[hz])
	except KeyError:
		print('没找到该汉字的拼音。')
		continue
	except EOFError:
		break
